package com.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * @Author: Jiangxx
 * @Date: 2021/11/19
 * @Description: 生产者
 */
public class ProducerFastStart {
    private static final String brokerList = "192.168.2.154:9092";
    private static final String topic = "topic-demo";
    /**
     * 配置生产者客户端参数
     * @return
     */
    public static Properties initConfig() {
        Properties properties = new Properties();
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList);
        properties.put(ProducerConfig.RETRIES_CONFIG, 10);
        return properties;
    }
    public static void main(String[] args) {
        /* 1.获取生产者客户端参数 */
        Properties props = initConfig();

        /* 2.创建生产者实例 */
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(props);

        /* 3.构建待发送的消息 */
        //ProducerRecord<String, String> record = new ProducerRecord<>(topic, "Hello,Litchi shell!");

        try {
            /* 4.发后即忘 kafkaProducer.send(record);*/

            /* 4.同步发送消息
            Future<RecordMetadata> future = kafkaProducer.send(record);
            RecordMetadata metadata = future.get();
            System.out.println(metadata.topic() + "-" + metadata.partition() + ":" + metadata.offset());*/

            /* 4.异步发送消息 */
//            kafkaProducer.send(record, new Callback() {
//                @Override
//                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
//                    if (e != null) {
//                        e.printStackTrace();
//                    } else {
//                        System.out.println(recordMetadata.topic() + "-" + recordMetadata.partition() + ":" + recordMetadata.offset());
//                    }
//                }
//            });
            int i = 0;
            while (i < 100000) {
                long l = System.currentTimeMillis();
                ProducerRecord<String, String> record = new ProducerRecord<>(topic, "msg"+i+"-生产时间："+ l);
                kafkaProducer.send(record);
                System.out.println("msg"+i+"-生产时间："+ l);
                i++;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        /* 5.关闭生产者实例 */
        kafkaProducer.close();
    }
}
